<?php

namespace App\Http\Controllers\School;

use App\Http\Requests\School\EditFood;
use App\Http\Requests\School\StoreFood;
use App\Http\Resources\School\FoodResource;
use App\Models\Food;
use App\Models\SchoolAdminLog;
use Illuminate\Http\Request;

/**
 * Class FoodController
 * @package App\Http\Controllers\School
 * 学校后台菜品管理
 */
class FoodController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     * 菜品列表
     */
    public function index(Request $request)
    {
        $foods = Food::orderBy('created_at', 'desc')
            ->with('type.school')->with('school.rule')
            ->where('school_id', \Auth::user()->school_id)
            ->foodTypeIs($request->food_type)
            ->supplyTypeIs($request->supply_type)
            ->nameLike($request->name)
            ->paginate($request->size);
        return FoodResource::collection($foods);
    }

    /**
     * @param StoreFood $request
     * @return FoodResource|array
     * 新增菜品
     */
    public function store(StoreFood $request)
    {
        $food = Food::create(array_merge($request->all(), [
            'school_id' => \Auth::user()->school_id
        ]));
        SchoolAdminLog::Log('新增菜品: ' . $food->name);
        return new FoodResource($food);
    }

    /**
     * @param EditFood $request
     * @param Food $food
     * @return FoodResource|array
     * 编辑菜品
     */
    public function update(EditFood $request, Food $food)
    {
        $food->fill($request->all());
        $food->save();
        SchoolAdminLog::Log('编辑菜品: ' . $food->name);
        return new FoodResource($food);
    }

    /**
     * @param Food $food
     * @return FoodResource
     * @throws \Exception
     * 删除菜品
     */
    public function destroy(Food $food)
    {
        $food->delete();
        SchoolAdminLog::Log('删除菜品: ' . $food->name);
        return new FoodResource($food);
    }
}
